import { h } from "preact";
import { useEffect, useRef, useState } from "preact/hooks";
import { JSX } from "preact";

// 为wangEditor添加全局类型声明
declare global {
  interface Window {
    wangEditor: {
      createEditor: (config: any) => any;
      createToolbar: (config: any) => any;
    }
  }
}

export interface RichTextEditorProps {
  value?: string;
  onChange?: (html: string) => void;
  placeholder?: string;
  className?: string;
  height?: string;
}

export default function RichTextEditor({
  value = "",
  onChange,
  placeholder = "请输入内容...",
  className = "",
  height = "300px"
}: RichTextEditorProps) {
  const editorRef = useRef<HTMLDivElement>(null);
  const toolbarRef = useRef<HTMLDivElement>(null);
  const [editor, setEditor] = useState<any>(null);
  
  // 初始化编辑器
  useEffect(() => {
    // 加载 wangEditor 样式
    const linkElement = document.createElement('link');
    linkElement.rel = 'stylesheet';
    linkElement.href = 'https://unpkg.com/@wangeditor/editor@latest/dist/css/style.css';
    document.head.appendChild(linkElement);
    
    // 加载 wangEditor 脚本
    const scriptElement = document.createElement('script');
    scriptElement.src = 'https://unpkg.com/@wangeditor/editor@latest/dist/index.js';
    
    // 脚本加载完成后初始化编辑器
    scriptElement.onload = () => {
      if (!editorRef.current || !toolbarRef.current || !window.wangEditor) return;
      
      const { createEditor, createToolbar } = window.wangEditor;
      
      // 创建编辑器实例
      const newEditor = createEditor({
        selector: editorRef.current,
        html: value,
        config: {
          placeholder
        },
        mode: 'default'
      });
      
      // 创建工具栏
      createToolbar({
        editor: newEditor,
        selector: toolbarRef.current,
        config: {
          toolbarKeys: [
            'headerSelect',
            '|',
            'bold',
            'italic',
            'underline',
            'through',
            'code',
            'sub',
            'sup',
            '|',
            'fontSize',
            'fontFamily',
            'lineHeight',
            'foreColor',
            'backColor',
            'clearStyle',
            'insertImage',
            'emotion',
            'insertTable',
            'codeBlock',
            'divider',
            '|',
            'bulletedList',
            'numberedList',
            'todo',
            'justifyLeft',
            'justifyRight',
            'justifyCenter',
            'justifyJustify',
            '|',
            'undo',
            'redo',
          ]
        }
      });

      // 设置change事件处理器
      newEditor.on('change', () => {
        if (onChange) {
          onChange(newEditor.getHtml());
        }
      });
      
      setEditor(newEditor);
    };
    
    // 添加脚本到文档
    document.head.appendChild(scriptElement);
    
    // 清理函数
    return () => {
      if (editor) {
        editor.destroy();
        setEditor(null);
      }
      // 移除脚本和样式表以避免多次加载
      document.head.removeChild(scriptElement);
      if (document.head.contains(linkElement)) {
        document.head.removeChild(linkElement);
      }
    };
  }, []);
  
  // 当value属性改变时更新编辑器内容
  useEffect(() => {
    if (editor && value !== editor.getHtml()) {
      editor.setHtml(value);
    }
  }, [value, editor]);
  
  return (
    <div className={`rich-text-editor ${className}`}>
      <div className="toolbar-container border border-gray-300 rounded-t-md" ref={toolbarRef}></div>
      <div 
        className="editor-container border border-gray-300 border-t-0 rounded-b-md p-2" 
        ref={editorRef}
        style={{ height }}
      ></div>
    </div>
  );
} 